/**
 * 文件名：****.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：*****
 */
package com.lightkits.wms.domain.purchasereceive;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.TransactionValidate;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.ScmPoHeader;
import com.lightkits.common.db.entity.ScmPoLine;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.framework.common.utility.validate.IntegrityValidator;
import com.lightkits.framework.soa.hzero.executor.ServiceExecutor;
import com.lightkits.wms.database.dao.WmsScmPoLineMapper;
import com.lightkits.wms.database.model.PurLineModel;
import com.lightkits.wms.domain.purchasereceive.service.PurHeadDomain;
import com.lightkits.wms.domain.stocktransfer.service.impl.SubStockTransferDomainImpl;
import com.lightkits.wms.dto.purchasereceive.GetPurListRequestType;
import com.lightkits.wms.dto.purchasereceive.GetPurListResponseType;
import com.lightkits.wms.dto.purchasereceive.models.PoHeadDTO;
import com.lightkits.wms.dto.purchasereceive.models.PoLineDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 采购订单行列表查询
 *
 * @author jing.wei@hand-china.com
 * Created on 2019/4/25 22:03
 */
@Component
public class PurListExecutor implements
        ServiceExecutor<GetPurListRequestType, GetPurListResponseType> {
    private final PurHeadDomain purHeadDomain;
    private static final Logger LOGGER = LoggerFactory.getLogger(SubStockTransferDomainImpl.class);

    @Autowired
    public PurListExecutor(PurHeadDomain purHeadDomain) {
        this.purHeadDomain = purHeadDomain;
    }

    @Autowired
    private WmsScmPoLineMapper scmPoLineMapper;

    /**
     * 采购订单列表查询服务
     *
     * @param request 采购订单请求参数
     * @return GetPurListResponseType
     **/
    @Override
    public GetPurListResponseType service(GetPurListRequestType request) {
        GetPurListResponseType response = new GetPurListResponseType();
        response.setSuccessful(true);
        try {
            IntegrityValidator.begin().validate(request.getPoId(), "Purcharse Id");

            TransactionValidate check = TransactionValidate.beginValidity(ScmPoHeader.class);
            check.checkIdValidity(ObjectUtil.toString(request.getPoId()), "ID");

            check = TransactionValidate.beginValidity(ScmPoLine.class);
            check.checkIdValidity(ObjectUtil.toString(request.getPoLineId()), "ID");

            PoHeadDTO headDTO = purHeadDomain.getHead(request.getPoId());
            response.setHeadDTO(headDTO);
            List<PurLineModel> models = scmPoLineMapper.getPoLineListById(request.getPoId(), request.getPoLineId());
            if (ObjectUtil.isNullOrEmpty(models)) {
                response.setLineDTOS(new ArrayList<>());
                return response;
            }
            response.setLineDTOS(this.convertLine(models));
        } catch (LightKitsBizException e) {
            response.setSuccessful(false);
            String mes = StringUtils.substringAfterLast(e.getMessage(), ":");
            response.setMessage(ObjectUtil.isNullOrEmpty(mes) ? e.getMessage() : mes);
        } catch (Exception e) {
            e.printStackTrace();
            response.setSuccessful(false);
            response.setMessage("get Purchase List Error");
        }
        return response;
    }

    /**
     * 采购订单转换
     *
     * @param models 采购订单行信息
     * @return List<PoLineDTO>
     **/
    private List<PoLineDTO> convertLine(List<PurLineModel> models) {
        List<PoLineDTO> dtos = new ArrayList<PoLineDTO>();
        SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
        try {
            models.forEach(model -> {
                PoLineDTO dto = new PoLineDTO();
                dto.setPoLineId(model.getPoLineId());
                dto.setItemId(model.getItemId());
                dto.setItemCode(model.getItemCode());
                dto.setItemDesc(model.getItemDesc());
                //根据单位中deciamal_number字段的保留小数位
                FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                        .eq(FndUomBase.UOM_CODE, model.getUomCode()));
                if (ObjectUtil.isEmpty(uomBase)) {
                    dto.setDemandQty(model.getDemandQty().toString());
                    dto.setReceiveQty(model.getReceiveQty().toString());
                } else {
                    dto.setReceiveQty(model.getReceiveQty()
                            .setScale(uomBase.getDecimalNumber().intValue(),
                                    BigDecimal.ROUND_HALF_UP).toString());
                    dto.setDemandQty(model.getDemandQty()
                            .setScale(uomBase.getDecimalNumber().intValue(),
                                    BigDecimal.ROUND_HALF_UP).toString());
                }
                dto.setDemandDate(df.format(model.getDemandDate()));
                dto.setUomCode(model.getUomCode());
                dto.setUomId(model.getUomId());
                dto.setUomName(model.getUomName());
                dto.setReceiveWarehouseId(model.getReceiveWarehouseId());
                dto.setReceiveWarehouseName(model.getReceiveWarehouseName());
                dtos.add(dto);
            });
        } catch (Exception e) {
            LOGGER.error("Po convertLine.error", e);
            throw new LightKitsBizException(e);
        }
        return dtos;
    }
}
